<?php
/**
 * Created by PhpStorm.
 * User: zcq
 * Date: 2018/10/16
 * Time: 15:34
 */

namespace app\admin\service;


use app\admin\model\VoteData;
use app\admin\model\VoteItems;
use app\admin\model\VoteType;
use think\Db;
use think\Exception;
use think\Validate;

class VoteItemsService extends BaseService
{
    public $model;
    public $typeModel;
    public $dataModel;
    const TABLE_TYPE = 'vote_type';

    public function __construct()
    {
        parent::__construct();
        $this->model = new VoteItems();
        $this->typeModel = new VoteType();
        $this->dataModel = new VoteData();
    }

    public function getPagination($voteId, $keyword, $type_id, $orderBy, $order)
    {
        $where['a.vote_id'] = ['eq', $voteId];
        if ($keyword) {
            $where['a.name|a.mid'] = ['like', '%' . $keyword . '%'];
        }
        if ($type_id) {
            $where['a.vote_type_id'] = ['eq', $type_id];
        }
        if ($orderBy) {
            $o = $order == 'desc' ? 'a.' . $orderBy . ' desc,a.id asc' : 'a.' . $orderBy . ' asc,a.id asc';
        } else {
            $o = $order == 'asc' ? 'a.id asc' : 'a.id desc';
        }
        $data['list'] = $this->model
            ->alias('a')
            ->join(self::TABLE_TYPE . ' b', 'b.id=a.vote_type_id', 'left')
            ->where($where)
            ->order($o)
            ->field('a.*,b.name as type_name')
            ->paginate();
        $data['page'] = $data['list']->render();
        return $data;
    }

    public function getList($voteId)
    {
        $data = $this->model
            ->alias('a')
            ->join(self::TABLE_TYPE . ' b', 'b.id=a.vote_type_id', 'left')
            ->where('a.vote_id', $voteId)
            ->order('a.id asc')
            ->field('a.*,b.name as type_name')
            ->select();
        return $data;
    }

    public function save($params)
    {
        $params['vote_type_id'] = $params['vote_type_id'] ?? 0;
        $validate = new Validate($this->model->rules);
        if (!$validate->check($params))
            return dataReturn(0, $validate->getError());
        $data = [
            'vote_id' => $params['vote_id'],
            'vote_type_id' => $params['vote_type_id'] ?? 0,
            'name' => $params['name'],
            'mid' => $params['mid'],
            'type_no' => $params['type_no'] ?? '',
            'info_pick' => $params['info_pick'],
            'head_img' => $params['head_img'] ?? '',
            'img' => $params['img'] ?? '',
            'info' => $params['info'] ?? '',
            'description' => $params['description'] ?? "",
            'video_url' => $params['video_url'] ?? '',
            'modtime' => time(),
            'addtime' => time(),
            'extra' => 0,
            'real' => 0,
            'remark' => $params['remark'] ?? '',
            'enable' => $params['enable'] ?? 1,
            'sort' => $params['sort'] ?? 0,
            'display' => $params['display'] ?? 0,
        ];

        if ($params['id']) {
            $res = $this->model->where('id', $params['id'])->update($data);
        } else {
            $res = $this->model->insert($data);
        }


        if ($res) {
            //清除缓存
            $this->clearVoteItems($params['vote_id']);
            return dataReturn(1, '保存成功');
        } else {
            return dataReturn(0, '保存失败');
        }
    }

    public function updateByField($params)
    {
        if ($params['field'] == 'name' && emptys($params['value']))
            return dataReturn(0, '不能为空');

        $data[$params['field']] = $params['value'];
        $data['modtime'] = time();
        if ($params['field'] == 'mid' || $params['field'] == 'extra') {
            $data[$params['field']] = (int)$params['value'];
        }
        if ($params['field'] == 'extra') {
            $a = $this->model->where('id', $params['id'])->find();
            $data['total'] = $a['real'] + $params['value'];
        }
        $res = $this->model->where('id', $params['id'])->update($data);

        if ($res) {
            //清除缓存
            $vote = $this->model->find($params['id']);
            $this->clearVoteItems($vote['vote_id']);
            return dataReturn(1, '保存成功');
        } else {
            return dataReturn(0, '保存失败');
        }
    }

    /**
     * @param $voteId
     * @param $id
     * 删除参赛数据
     */
    public function del($voteId, $id)
    {
        if ($id) {
            $res = $this->model->where('id', $id)->where('vote_id', $voteId)->delete();
        } else {
            Db::startTrans();
            try {
                $res1 = $this->model->where('vote_id', $voteId)->delete();
                $type = $this->typeModel->where('vote_id', $voteId)->find();
                $res2 = true;
                if ($type) {
                    $res2 = $this->typeModel->where('vote_id', $voteId)->delete();
                }
                if ($res1 && $res2) {
                    Db::commit();
                    //清除缓存
                    $this->clearVoteItems($voteId);
                    return true;
                }
                Db::rollback();
                return false;
            } catch (Exception $exception) {
                Db::rollback();
                return false;
            }
        }
        if ($res) {
            //清除缓存
            $this->clearVoteItems($voteId);
        }
        return $res;
    }

    public function find($id)
    {
        return $this->model->where('id', $id)->find();
    }

    /**
     * @param $params
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 批量插入参赛数据
     */
    public function batch($params)
    {
        if (empty($params['name_field']) || empty($params['id_field']) || empty($params['img']))
            return dataReturn(0, '参数错误');
        if (!isset($params['is_tag']) || ($params['is_tag'] == 1 && empty($params['tag_field'])))
            return dataReturn(0, '参数错误');

        $json = file_get_contents('.' . $params['img']);
        $arr = json_decode($json, 1);
        if (empty($arr['data']))
            return dataReturn(0, '数据为空');

        $data = [];
        $total = 0;
        Db::startTrans();
        try {
            //分类
            if ($params['is_tag']) {
                $tagId = '';
                foreach ($arr['data'] as $v) {
                    $mid = $v[$params['id_field']] ?? '';
                    if ($mid == '') {
                        continue;
                    }
                    $name = $v[$params['name_field']] ?? '';

                    if (strstr($mid, $params['tag_field'])) {
                        //查找分类是否存在
                        $tag = $this->typeModel
                            ->where('vote_id', $params['vote_id'])
                            ->where('type_no', $mid)
                            ->find();
                        if (!$tag) {
                            $tagModel = [
                                'vote_id' => $params['vote_id'],
                                'name' => $name,
                                'type_no' => $mid,
                                'pid' => 0,
                                'level' => 1,
                                'addtime' => time(),
                                'modtime' => time(),
                            ];
                            $tagId = $this->typeModel->insertGetId($tagModel);
                        } else {
                            $tagId = $tag['id'];
                        }

                        if (!$tagId) {
                            Db::rollback();
                            return dataReturn(0, '保存失败');
                        }
                    } else if ($tagId) {
                        $data[] = [
                            'vote_id' => $params['vote_id'],
                            'vote_type_id' => $tagId,
                            'mid' => $mid,
                            'name' => $name,
                            'remark' => '',
                            'real' => 0,
                            'extra' => 0,
                            'total' => 0,
                            'addtime' => time(),
                            'modtime' => time(),
                        ];
                    }
                }
            }
            //不需分类的
            if (!$params['is_tag']) {
                foreach ($arr['data'] as $v) {
                    $mid = $v[$params['id_field']] ?? '';
                    if ($mid == '') {
                        continue;
                    }
                    $name = $v[$params['name_field']] ?? '';
                    $data[] = [
                        'vote_id' => $params['vote_id'],
                        'vote_type_id' => 0,
                        'mid' => $mid,
                        'name' => $name,
                        'remark' => '',
                        'real' => 0,
                        'extra' => 0,
                        'total' => 0,
                        'addtime' => time(),
                        'modtime' => time(),
                    ];
                }
            }
            $count = count($data);
            if ($count) {
                $total = $this->model->insertAll($data);
                if ($total != $count) {
                    Db::rollback();
                    return dataReturn(0, '保存失败');
                }
            }
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            return dataReturn(0, '保存失败');
        }
        //清除缓存
        $this->clearVoteItems($params['vote_id']);
        return dataReturn(1, '保存成功', $total);
    }

    public function getDataList($ids)
    {
        $data = [];
        foreach ($ids as $v) {
            $item = $this->model->find($v);
            if ($item) {
                $item['list'] = $this->dataModel
                    ->where('vote_item_id', $v)
                    ->where('is_del', $this->dataModel::DEL_FALSE)
                    ->order('id asc')
                    ->select();
                $data[] = $item;
            }
        }
        return $data;
    }

}